<template>
  <div>
    <div class="mb-4">
      <el-button
        type="success"
        size="default"
        v-if="isExamineRole"
        @click="onPass"
        ><el-icon><DocumentChecked /></el-icon>审核通过</el-button
      >
      <el-button
        type="danger"
        size="default"
        @click="FailAudit"
        v-if="isExamineRole"
        ><el-icon><DocumentDelete /></el-icon>审核不通过</el-button
      >
      <el-button
        type="primary"
        size="default"
        :disabled="ischeckstatus === 1"
        @click="onProofread"
        ><el-icon><Check /></el-icon>校对</el-button
      >
      <!-- <el-button type="warning" size="default"
        ><el-icon><HomeFilled /></el-icon>前台预览</el-button
      > -->
    </div>
    <!-- 弹窗部分 -->
    <el-dialog
      v-model="dialogVisible"
      title="退回原因"
      width="500"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-input v-model="reason"></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button :disabled="!reason" type="primary" @click="onSubmitRefuse">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <div>
      <div class="page">
        <el-container>
          <el-header>
            <el-row>
              <!-- 页面标题 -->
              <el-col :span="24">
                <div class="title" v-html="pageData.title"></div>
              </el-col>
              <el-col :span="24">
                <el-text class="info">
                  <span>发布者: {{ pageData.publisher }}</span>
                  <span style="margin-left: 20px"
                    >预约发布时间: {{ pageData.scheduledTime }}</span
                  >
                </el-text>
              </el-col>
            </el-row>

            <!-- 页面信息 -->
            <el-row> </el-row>
            <el-divider />
          </el-header>
          <el-main>
            <el-row>
              <div class="content" style="margin: 0 auto">
                <!-- 内容 -->
                <div v-html="pageData.contentTexT" class="contentText"></div>
              </div>
            </el-row>
            <el-divider
          /></el-main>
          <el-footer>
            <!-- 附件 -->
            <el-row v-if="pageData.attachments.length !== 0">
              <el-col :span="24">
                <el-text class="attachment-title">附件</el-text>
                <el-text class="attachment-info">
                  <span
                    v-for="(attachment, index) in pageData.attachments"
                    :key="attachment.uuid"
                    style="font-size: 12px; color: #0769b2; cursor: pointer"
                    @click="downloadFn(attachment)"
                  >
                    {{ `附件${index + 1}： ${attachment.attachment_name}` }}
                  </span>
                </el-text>
              </el-col>
            </el-row>
            <el-divider
          /></el-footer>
        </el-container>
      </div>
    </div>
  </div>
</template>
<script setup>
import { useRoute, useRouter } from 'vue-router'
import { onMounted, ref } from 'vue'
import { useStore } from 'vuex'
import {
  contentDetail,
  downloadContent,
  auditCheck,
  auditCheckFalse,
  proofread
} from '@/api/content/contentList'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
const route = useRoute()
const router = useRouter()
const dialogVisible = ref(false)
const reason = ref()
const pageData = ref({
  title: '',
  publisher: '',
  scheduledTime: '',
  attachments: [],
  contentTexT: ''
})
const ischeckstatus = ref(0)
const isExamineRole = ref(true)
const store = useStore()
const buttonRole = store.state.app.buttonRole
const userId = store.state.app.user.id
onMounted(() => {
  getDetail()
})
const getDetail = async () => {
  // 按钮权限
  buttonRole.map((item) => {
    if ('内容管理'.includes(item.name)) {
      item.children.map((list) => {
        if (list.name === '内容审核') {
          if (list.isbutton) {
            isExamineRole.value = true
          } else {
            isExamineRole.value = false
          }
        }
      })
    }
  })
  await contentDetail(route.query.id).then((res) => {
    pageData.value.title = res.data.contentExt.title
    pageData.value.publisher = res.data.username
    pageData.value.scheduledTime = dayjs(res.data.releaseDateMain).format(
      'YYYY-MM-DD HH:mm:ss'
    )
    pageData.value.attachments = res.data.contentAttachmentList
    pageData.value.contentTexT = res.data.contentTexT
    ischeckstatus.value = res.data.checkstatus
  })
}
const downloadFn = async (attachment) => {
  try {
    const response = await downloadContent(attachment.uuid)
    // 确保 response 和 response.data 存在
    if (!response || !response.data) {
      throw new Error('No data received from server')
    }
    // 创建 Blob 对象
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/octet-stream'
    })
    const filename = attachment.attachment_name
    // 创建一个临时的 <a> 元素用于下载
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = filename

    // 将 <a> 元素添加到 DOM 中并触发点击事件
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    // 释放 Blob URL 资源
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('Download failed:', error.message || error)
  }
}
const FailAudit = () => {
  reason.value = ''
  dialogVisible.value = true
}
// 审核通过
const onPass = () => {
  auditCheck({ content_id: route.query.id, user_id: userId })
    .then((res) => {
      ElMessage.success(res.message)
      router.push('ContentManagementList')
    })
    .catch((err) => {
      console.log(err)
    })
}
// 不通过原因
const onSubmitRefuse = () => {
  auditCheckFalse({
    content_id: route.query.id,
    user_id: userId,
    check_opinion: reason.value
  })
    .then((res) => {
      ElMessage.success(res.message)
      router.push('ContentManagementList')
    })
    .catch((err) => {
      console.log(err)
    })
}
// 校对
const onProofread = () => {
  proofread({
    content_id: route.query.id,
    user_id: userId
  })
    .then((res) => {
      ElMessage.success(res.message)
      router.push('ContentManagementList')
    })
    .catch((err) => {
      console.log(err)
    })
}
</script>

<style lang="scss" scoped>
.title {
  display: flex;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  margin: 20px 0;
  text-align: center;
}

.info {
  display: flex;
  justify-content: center;
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.attachment-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.attachment-info {
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
}
:deep(.el-header) {
  --el-header-height: !important;
}
</style>
<style lang="scss">
.contentText {
  p {
    img {
      max-width: 100% !important; /* 图片最大宽度为容器宽度 */
      height: auto;
    }
  }
  video{
    width: 100%;
  }
}
</style>
